<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}`">
    <el-form
      ref="bannerFormRef"
      label-width="120px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      v-if="drawerProps.row"
    >
      <el-form-item label="banner名称" prop="bannerName">
        <el-input v-model="drawerProps.row!.bannerName" placeholder="请填写banner名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="banner类型" prop="bannerType">
        <el-select v-model="drawerProps.row!.bannerType" placeholder="请选择banner类型" clearable>
          <el-option label="规章制度" :value="1" />
          <el-option label="实验场景" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="图片" prop="bannerFileIds">
        <el-upload
          class="avatar-uploader"
          list-type="picture-card"
          v-model:file-list="fileList"
          :on-preview="handlePictureCardPreview"
          :before-remove="handleBeforeRemove"
          :on-remove="handleRemove"
          :http-request="_uploadFile"
        >
          <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="drawerProps.row!.status" placeholder="请选择状态" clearable>
          <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
    <el-image-viewer @close="dialogVisible = false" :url-list="dialogImageUrl" v-if="dialogVisible" />
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive } from "vue";
import { status } from "@/utils/serviceDict";
import { ElMessage, FormInstance, UploadProps, UploadRequestOptions, UploadUserFile } from "element-plus";
import { Banner } from "@/api/interface";

import { uploadFile } from "@/api/modules/common";
import { Plus } from "@element-plus/icons-vue";
import { VITE_API_URL } from "@/config/index";

const bannerPicList: any = ref([]);
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl: any = ref([]);
const dialogVisible = ref(false);
const rules = reactive({
  bannerName: [{ required: true, message: "请填写banner名称" }],
  bannerType: [{ required: true, message: "请选择banner类型" }],
  status: [{ required: true, message: "请选择状态" }],
  bannerFileIds: [{ required: true, message: "请上传图片" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Banner.ResBannerList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  bannerPicList.value = [];
  fileList.value = [];
  if (drawerProps.value.title === "编辑") {
    bannerPicList.value = drawerProps.value.row.bannerFileIds?.split(",").map(item => item);
    fileList.value = drawerProps.value.row.bannerFileIds?.split(",").map((item: string) => {
      return {
        name: item,
        url: `${VITE_API_URL}/file/download/${item}`
      };
    }) as UploadUserFile[];
  }
};

// 提交数据（新增/编辑）
const bannerFormRef = ref<FormInstance>();
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  bannerFormRef.value && bannerFormRef.value.resetFields();
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  bannerFormRef.value!.validate(async valid => {
    if (!valid) return;

    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

/**
 * 文件上传
 */
const _uploadFile = (uploadFileOpts: UploadRequestOptions) => {
  return new Promise<void>((resolve, reject) => {
    const file = uploadFileOpts!.file;
    const site = file.name.lastIndexOf("\.");
    const fileName = file.name.substring(0, site);
    const fileSuffix = file.name.substring(site + 1, file.name.length);

    const imgTypelist = ["png", "jpg", "jpeg", "gif"];
    if (!imgTypelist.includes(fileSuffix)) {
      ElMessage.error("文件类型不匹配或不支持该种类型文件");
      return false;
    }
    filetoBase64(file as File).then(async (base64Value: any) => {
      if (base64Value.indexOf("base64,") != -1) {
        base64Value = base64Value.substr(base64Value.indexOf("base64,") + 7);
      }
      try {
        const res = await uploadFile({
          fileType: "deviceDevOps",
          fileContent: base64Value,
          fileName,
          fileSuffix
        });
        fileList.value.pop();
        fileList.value.push({
          name: res.fileId,
          url: `${VITE_API_URL}/file/download/${res.fileId}`
        });
        bannerPicList.value.push(res.fileId);
        drawerProps.value.row!.bannerFileIds = bannerPicList.value.join(",");
        console.log(fileList);
        resolve();
      } catch (error) {
        fileList.value.pop();
        reject();
      }
    });
  });
};
/**
 * 删除图片前数据处理
 */
const handleBeforeRemove: UploadProps["beforeRemove"] = uploadFile => {
  const fileIdx = fileList.value.findIndex(item => item.name === uploadFile.name);
  bannerPicList.value.splice(fileIdx, 1);
  drawerProps.value.row!.bannerFileIds = bannerPicList.value.join(",");
  return true;
};
/**
 * 删除图片
 */
const handleRemove: UploadProps["onRemove"] = uploadFile => {
  console.log(uploadFile);
};

/**
 * 预览图片
 */
const handlePictureCardPreview: UploadProps["onPreview"] = uploadFile => {
  dialogImageUrl.value = [uploadFile.url!];
  dialogVisible.value = true;
};
const filetoBase64 = (file: File) => {
  let reader = new FileReader(); //实例化文件读取对象
  reader.readAsDataURL(file); //将文件读取为 DataURL,也就是base64编码
  return new Promise(reslove => {
    reader.onload = e => {
      //文件读取成功完成时触发
      if (e.target) {
        let dataURL = e.target.result; //获得文件读取成功后的DataURL,也就是base64编码
        reslove(dataURL);
      }
    };
  });
};

defineExpose({
  acceptParams
});
</script>
<style lang="scss" scoped>
.el-dialog__header {
  border-bottom: 0;
}
</style>

<style>
.avatar-uploader .el-upload {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.avatar-uploader .el-upload-list__item {
  width: 100px;
  height: 100px;
}
</style>
